<?php namespace App\Application;

use App\Exceptions\Item\OrderException;
use App\Models\ItemOrder;
use App\Models\ItemOrderPayment;
use App\Repositories\Order\OrderRepositoryInterface;
use Carbon\Carbon;

class PayService
{
    /**
     * @var OrderRepositoryInterface
     */
    protected $order_repository;

    public function __construct()
    {
        $this->order_repository = app(OrderRepositoryInterface::class);
    }

    /**
     * 支付成功
     *
     * @param ItemOrder $order
     * @param           $pay_trade_no
     * @param           $end_time
     */
    public function success(ItemOrder $order, $pay_trade_no, $end_time)
    {
        if (is_numeric($end_time)) {
            $end_time = date('Y-m-d H:i:s', $end_time);
        }
        if ($order->isPaidSuccess()) {
            return false;
        }

        $this->order_repository->paySuccess($order, $pay_trade_no, $end_time);

        //发起结算倒计时
        $this->storePayment($order);
    }

    /**
     * 支付失败
     *
     * @param ItemOrder $order
     * @param           $out_trade_no
     * @param           $end_time
     *
     * @return bool
     */
    public function failure(ItemOrder $order, $out_trade_no, $end_time)
    {
        return $this->order_repository->payFailure($order, $out_trade_no, $end_time);
    }

    /**
     * 发起待回款项
     *
     * @param ItemOrder $order
     *
     * @return bool
     */
    private function storePayment(ItemOrder $order)
    {
        $model = new ItemOrderPayment();
        $model->status = ItemOrderPayment::STATUS_PENDING;
        $model->publisher_uid = $order->publisher_uid;
        $model->order_id = $order->id;
        $second = env('PAYMENT_COUNT_DOWN_SECOND');
        $model->date = Carbon::now()->addSeconds($second)->toDateTimeString();

        $platform_rate = env('ORDER_PLATFORM_COMMISSION_RATE');
        if ($platform_rate > 50) {
            $platform_rate = 50;
        }
        $platform_money = sprintf('%.2f', $order->money * $platform_rate / 100);
        $model->total_money = $order->money;
        $model->platform_money = $platform_money;
        $model->publisher_money = bcsub($order->money, $platform_money, 2);

        return $model->save();
    }
}
